package com.socialmediaanalytics.client.recomendations;

import java.util.Arrays;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.socialmediaanalytics.client.GWTEntryPoint;
import com.socialmediaanalytics.client.facebook.FacebookImage;



/** 
 * Show the Top 5 books that the top 5 facebook friends most like.TODO: Show the name of the book on the image title.
 * 
 * @ToDo
 * @Feature 
 */

public class ShowBookRecommendations extends VerticalPanel {

	public static HorizontalPanel panelBooks = new HorizontalPanel();

	public ShowBookRecommendations() {

		this.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

		HTML title = new HTML("<b>Recommended Books</b>");
		this.add(title);

		title.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				showBooks();
			}
		});

		panelBooks.clear();

		panelBooks.setSpacing(3);

		this.add(panelBooks);

	}

	public static void showBooks() {

		panelBooks.clear();

		Object[] values = GWTEntryPoint.facebookRecommendedBooks.values()
				.toArray();

		Arrays.sort(values);

		int last5 = 0;
		if (values.length > 5) {

			last5 = Integer.parseInt(values[values.length - 5].toString());
		} else {

			if (values.length > 0) {

				last5 = Integer.parseInt(values[0].toString());
			}
		}

		int i = 0;

		for (String bookID : GWTEntryPoint.facebookRecommendedBooks.keySet()) {

			if (i < 5
					&& GWTEntryPoint.facebookRecommendedBooks.get(bookID) >= last5) {

				// if (GWTEntryPoint.facebookRecommendedBooks.get(bookID) > 1) {

				String image = FacebookImage.getString(bookID, "");

				HTML book = new HTML("<br><br>" + image + "<br>"
						+ GWTEntryPoint.facebookRecommendedBooks.get(bookID));

				panelBooks.add(book);
				// }
				i++;
			}
		}
	}

	public static void getRecommendedBooks(String friendID) {

		for (String bookID : GWTEntryPoint.facebookFriends.get(friendID)
				.getFacebookBooks().keySet()) {

			if (GWTEntryPoint.facebookCommonBooks.get(bookID) == null) {

				if (GWTEntryPoint.facebookRecommendedBooks.get(bookID) != null) {

					GWTEntryPoint.facebookRecommendedBooks
							.put(bookID, GWTEntryPoint.facebookRecommendedBooks
									.get(bookID) + 1);
				} else {

					GWTEntryPoint.facebookRecommendedBooks.put(bookID, 1);
				}

			}
		}
	}

}
